package com.wst.system.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wst.system.config.exception.GlobalExcetion;
import com.wst.system.security.entity.SysMenuEntity;
import com.wst.system.security.entity.SysRoleEntity;
import com.wst.system.security.entity.SysUserEntity;
import com.wst.system.security.entity.SysUserRoleEntity;
import com.wst.system.security.entity.vo.SysUserEntityAddVo;
import com.wst.system.server.entity.vo.PageSearchVo;
import com.wst.system.server.mapper.SysUserMapper;
import com.wst.system.server.service.SysRoleService;
import com.wst.system.server.service.SysUserRoleService;
import com.wst.system.server.service.SysUserService;
import com.wst.system.util.JSONUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/11 14:51
 * @since JDK 1.8
 */
@Transactional
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {



    /**
     * 根据用户名查询实体
     * @Author Sans
     * @CreateTime 2019/9/14 16:30
     * @Param  username 用户名
     * @Return SysUserEntity 用户实体
     */
    @Override
    public SysUserEntity selectUserByName(String username) {
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserEntity::getUsername,username);
        return this.baseMapper.selectOne(queryWrapper);
    }

    @Override
    public SysUserEntity selectUserByPhone(String phone) {
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserEntity::getPhone,phone);
        return this.baseMapper.selectOne(queryWrapper);
    }

    @Override
    public SysUserEntity selectUserByEmail(String email) {
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserEntity::getPhone,email);
        return this.baseMapper.selectOne(queryWrapper);
    }

    /**
     * 通过用户ID查询角色集合
     * @Author Sans
     * @CreateTime 2019/9/18 18:01
     * @Param  userId 用户ID
     * @Return List<SysRoleEntity> 角色名集合
     */
    @Override
    public List<SysRoleEntity> selectSysRoleByUserId(Integer userId) {
        return this.baseMapper.selectSysRoleByUserId(userId);
    }

    /**
     * 根据用户ID查询权限集合
     * @Author Sans
     * @CreateTime 2019/9/18 18:01
     * @Param userId 用户ID
     * @Return List<SysMenuEntity> 角色名集合
     */
    @Override
    public List<SysMenuEntity> selectSysMenuByUserId(Integer userId) {
        return this.baseMapper.selectSysMenuByUserId(userId);
    }

    @Override
    public IPage<SysUserEntity> page(Integer pageNum, Integer pageSize, PageSearchVo vo) {
        LambdaQueryWrapper<SysUserEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(JSONUtil.containsKey(vo.getSearch(),"username")){
            lambdaQueryWrapper.like(SysUserEntity ::getUsername,vo.getString("username"));
        }
        if(JSONUtil.containsKey(vo.getSearch(),"phone")){
            lambdaQueryWrapper.like(SysUserEntity ::getPhone,vo.getString("phone"));
        }
        if(JSONUtil.containsKey(vo.getSearch(),"realname")){
            lambdaQueryWrapper.like(SysUserEntity ::getPhone,vo.getString("realname"));
        }
        if(JSONUtil.containsKey(vo.getSearch(),"email")){
            lambdaQueryWrapper.like(SysUserEntity ::getEmail,vo.getString("email"));
        }
        if(JSONUtil.containsKey(vo.getSearch(),"sex")){
            lambdaQueryWrapper.eq(SysUserEntity::getSex,vo.getString("sex"));
        }
        lambdaQueryWrapper.orderByDesc(SysUserEntity ::getCreateTime);
        IPage<SysUserEntity> page=super.baseMapper.selectPage(new Page(pageNum,pageSize),lambdaQueryWrapper);
        return page;
    }


    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleService  sysRoleService;

    @Override
    public SysUserEntity addUser(SysUserEntity user) throws GlobalExcetion {
        SysUserEntity sysUserEntity=this.selectUserByName(user.getUsername());
        if(sysUserEntity!=null){
            throw new GlobalExcetion(1,"用户账号已存在");
        }
        sysUserEntity=this.selectUserByPhone(user.getPhone());
        if(sysUserEntity!=null){
            throw new GlobalExcetion(1,"用户手机号已存在");
        }
        sysUserEntity=this.selectUserByEmail(user.getEmail());
        if(sysUserEntity!=null){
            throw new GlobalExcetion(1,"用户邮箱已存在");
        }
        String password=new BCryptPasswordEncoder().encode(user.getPassword());
        user.setPassword(password);
        user.setStatus("NORMAL");
        this.save(user);
        SysRoleEntity sysRoleEntity=sysRoleService.getSysRoleEntityByRoleNo("user");
        SysUserRoleEntity sysUserRoleEntity=new SysUserRoleEntity();
        sysUserRoleEntity.setUserId(user.getUserId());
        sysUserRoleEntity.setRoleId(sysRoleEntity.getRoleId());
        sysUserRoleService.save(sysUserRoleEntity);
        return user;
    }

    @Override
    public SysUserEntity saveOrUpdate(SysUserEntityAddVo vo) throws GlobalExcetion {
        SysUserEntity sysUserEntity = new SysUserEntity();

        BeanUtils.copyProperties(vo,sysUserEntity);
        if(vo.getUserId()!=null){
            SysUserEntity entiry=super.baseMapper.selectById(vo.getUserId());
            if(entiry==null){
                throw new GlobalExcetion(1,"数据不存在");
            }
            if(!vo.getUsername().equals(entiry.getUsername())){
                throw new GlobalExcetion(1,"禁止更改账号");
            }
            if(!entiry.getPhone().equals(vo.getPhone())){
                SysUserEntity phone=this.getSysUserByPhone(vo.getPhone());
                if(phone!=null){
                    throw new GlobalExcetion(1,"手机号已被他人绑定");
                }
            }
            if(!entiry.getEmail().equals(vo.getEmail())){
                SysUserEntity email=this.getSysUserByEmail(vo.getEmail());
                if(email!=null){
                    throw new GlobalExcetion(1,"邮箱已被他人绑定");
                }
            }
            super.baseMapper.updateById(sysUserEntity);
        }else{
            String password=new BCryptPasswordEncoder().encode("123456");
            sysUserEntity.setPassword(password);
            sysUserEntity.setStatus("NORMAL");
            SysUserEntity username=this.selectUserByName(vo.getUsername());
            if(username!=null){
                throw new GlobalExcetion(1,"账号已存在");
            }
            SysUserEntity email=this.getSysUserByEmail(vo.getEmail());
            if(email!=null){
                throw new GlobalExcetion(1,"邮箱已被他人绑定");
            }
            SysUserEntity phone=this.getSysUserByPhone(vo.getPhone());
            if(phone!=null){
                throw new GlobalExcetion(1,"手机号已被他人绑定");
            }
            super.baseMapper.insert(sysUserEntity);
        }
        return sysUserEntity;
    }



    @Override
    public SysUserEntity getSysUserByPhone(String phone) {
        LambdaQueryWrapper<SysUserEntity> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserEntity::getPhone,phone);
        return this.baseMapper.selectOne(lambdaQueryWrapper);
    }

    @Override
    public SysUserEntity getSysUserByEmail(String email) {
        LambdaQueryWrapper<SysUserEntity> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserEntity::getEmail,email);
        return this.baseMapper.selectOne(lambdaQueryWrapper);
    }

    @Override
    public void deleteIds(List<String> ids) {
        this.baseMapper.deleteBatchIds(ids);
    }
}
